<template>
  <div>
    <div class="app-container">
      <el-form ref="form" :model="form" :rules="rules" label-width="90px" label-position="left">
        <div class="examineTitle mb20">
          请假申请
        </div>
        <el-form-item label="请假类型" prop="isEmpty">
          <el-select v-model="form.type" placeholder="请选择请假类型" @change="leaveType()">
            <el-option :label="item.name" :value="item.id" v-for="item in ruleList"></el-option>
          </el-select>
        </el-form-item>
        <!--        unit: '', // 单位 1-天 2-半天 3-小时-->
        <el-form-item label="开始时间" prop="isEmpty">
          <el-col :span="5">
            <el-date-picker type="date" placeholder="请选择" v-model="startTimeDay" style="width: 100%;"
                            format="yyyy-MM-dd"
                            value-format="yyyy-MM-dd" :disabled="!this.form.type"></el-date-picker>
          </el-col>
          <el-col class="line" :span="1" v-if="unit==3||unit==2">-</el-col>
          <el-col :span="4" v-if="unit==3">
            <el-time-picker :disabled="!this.form.type" placeholder="请选择" v-model="startTimeSon" style="width: 100%;"
                            format="HH:mm"
                            value-format="HH:mm" @change="changetimeFn('start')"></el-time-picker>
          </el-col>
          <el-col :span="4" v-if="unit==2">
            <el-select v-model="halfDay_s" placeholder="请选择" @change="changeDayTime()">
              <el-option
                v-for="item in halfDay_list"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-col>
        </el-form-item>
        <el-form-item label="结束时间" prop="isEmpty">
          <el-col :span="5">
            <el-date-picker :disabled="!this.form.type" type="date" placeholder="请选择" v-model="endTimeDay"
                            style="width: 100%;" format="yyyy-MM-dd"
                            value-format="yyyy-MM-dd"></el-date-picker>
          </el-col>
          <el-col class="line" :span="1" v-if="unit==3||unit==2">-</el-col>
          <el-col :span="4" v-if="unit==3">
            <el-time-picker :disabled="!this.form.type" placeholder="请选择" v-model="endTimeSon" style="width: 100%;"
                            format="HH:mm"
                            value-format="HH:mm" @change="changetimeFn('end')"></el-time-picker>
          </el-col>
          <el-col :span="4" v-if="unit==2">
            <el-select v-model="halfDay_e" placeholder="请选择" @change="changeDayTime()">
              <el-option
                v-for="item in halfDay_list"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-col>
        </el-form-item>
        <el-form-item :label="`时长(${unit==3?'小时':'天'})`" prop="isEmpty">
          <el-input v-model="house" :placeholder="`${unit==3?'时长':'天'}`" disabled></el-input>
          <div class="tips-rule">
            根据排班自动计算时长 <span @click="timeRuleShow=true">查看明细</span>
          </div>
        </el-form-item>
        <el-form-item label="请假事由" prop="isEmpty">
          <el-input type="textarea" v-model="form.content" placeholder="请假事由"></el-input>
        </el-form-item>
        <el-form-item label="图片" class="my-dialog">
          <image-upload v-model="form.file" :limit="9" :isShowTip="false"/>
        </el-form-item>
      </el-form>
      <timeRule :visible.sync="timeRuleShow" :leaveDay="leaveDay" :time="form.time" :unit="unit"></timeRule>
    </div>
  </div>

</template>

<script>
import {leaveAdd} from "@/api/system/leave"
import {listLeaveUSer} from '@/api/system/leave_category'
import timeRule from "./timeRule";
import {mapGetters} from 'vuex'

export default {
  name: "index",
  components: {timeRule},
  props: ['flowData', 'deptOptions', 'workDay'],
  data() {
    return {
      activeName: 'first',
      form: {
        type: '', // 1-事假2-病假3-调休4-产假5-婚假6-例假7-哺乳假8-丧假
        startTime: '', // 开始时间
        endTime: '', // 结束时间
        time: '', // 时长
        content: '', // 原因
        file: '', // 附件
        flowId: '', // 审核流程id
        isEmpty: '1'
      },
      rules: {
        isEmpty: [
          {required: true, message: '不能为空', trigger: 'blur'},
        ],
      },
      startTimeDay: '',
      startTimeSon: '',
      endTimeDay: '',
      endTimeSon: '',
      ruleList: [], // 请假类型
      timeRuleShow: false,
      leaveDay: [],
      reverse: true,
      house: '',
      depetUser: [], // 用户本身的部门链
      userTime: 32, // 用户请假时长最后需要换算成天，先按照8小时一天计算

      unit: '', // 单位 1-天 2-半天 3-小时
      halfDay_s: '', // 开始的上午下午
      halfDay_e: '', // 结束的上午下午
      halfDay_list: [
        {
          value: 1,
          label: '上午'
        }, {
          value: 2,
          label: '下午'
        }
      ],
      leaveDetail: [],
      flagLoading: false
    }
  },
  computed: {
    ...mapGetters([
      'deptId',
      'userId'
    ]),
  },
  watch: {
    startTimeDay() {
      this.changeDayTime()
    },
    endTimeDay() {
      this.changeDayTime()
    },
  },
  created() {
    this.getruleList() // 请假类型
  },
  methods: {
    onSubmit(flowline) {
      console.log('submit!', flowline);
      let query_ = JSON.parse(JSON.stringify(this.form))
      let that = this
      if (!query_.type) {
        this.$message.error('选择请假类型')
        return
      }
      if (this.unit == 3 && (!this.startTimeDay || !this.startTimeSon || !this.endTimeDay || !this.endTimeSon)) {
        this.$message.error('选择请假时间')
        return
      }
      if (this.unit == 2 && (!this.startTimeDay || !this.halfDay_s || !this.endTimeDay || !this.halfDay_e)) {
        this.$message.error('选择请假时间')
        return
      }
      if (this.unit == 1 && (!this.startTimeDay || !this.endTimeDay)) {
        this.$message.error('选择请假时间')
        return
      }
      if (!query_.content) {
        this.$message.error('填写请假事由')
        return
      }
      // 提交的参数 examineLog
      // examineId 审核id
      // name 名称
      // content // 自定义
      // userIds  步骤审核人
      // isExamine  0-待审核1-通过2-驳回
      // type 1 全部用户审核，2 单个用户审核
      // isAuto 是否直接通过0否1是
      // style 1 审核 2 抄送
      let examinelog_ = []
      for (let item of flowline) {
        let userData_ = []
        if (item.userData) {
          for (let user of item.userData) {
            userData_.push(user.id)
          }
        }
        examinelog_.push({
          // item.assignedType
          examineId: 0, // 审核id
          name: item.exaName, // 名称
          content: '', //
          userIds: userData_.join(','), //  步骤审核人
          isExamine: 0, //  0-待审核1-通过2-驳回
          type: item.moreUserSign ? (item.moreUserSign == 'AND' ? 1 : 2) : 0, // 全部用户审核，1个用户审核
          isAuto: item.assignedType == 'AUTO_PASS' ? 1 : 0, // 是否直接通过0否1是
          style: item.assignedType == 'CC' ? 2 : 1, // 1 审核 2 抄送
        })
      }
      if (this.unit == 3) {
        query_.startTime = `${this.startTimeDay} ${this.startTimeSon}:00`
        query_.endTime = `${this.endTimeDay} ${this.endTimeSon}:00`
      } else {
        query_.startTime = `${this.startTimeDay} 00:00:00`
        query_.endTime = `${this.endTimeDay} 00:00:00`
      }
      if (this.unit == 2) {
        query_.startType = this.halfDay_s
        query_.endType = this.halfDay_e
      } else {
        query_.startType = 0
        query_.endType = 0
      }
      delete query_.isEmpty
      query_.flowId = this.flowData.id || 0
      query_.examineLog = examinelog_
      query_.unit = this.unit
      query_.detail = ''
      // startType 开始时间类型1上午2下午0无
      // endType 开始时间类型1上午2下午0无
      // unit 请假单位1-按天2-半天3-小时
      // console.log('审批流程条件', this.flowData)
      // console.log('部门树：', this.deptOptions)
      // this.checkExamine()
      if(this.flagLoading){
        return
      }
      this.flagLoading = true
      this.$modal.loading("正在保存中，请稍候...");
      leaveAdd(query_).then(res => {
        console.log('res===>', res)
        this.$message.success('提交成功')
        this.reset()
      })
      setTimeout(()=>{
        that.flagLoading = false
      }, 1000)
    },
    changetimeFn(type) {
      console.log('时间信息', type)
      this.changeDayTime()
    },
    // 请假类型变动了
    leaveType() {
      // form.type
      console.log('this.ruleList', this.ruleList, this.form.type)
      for (let item of this.ruleList) {
        if (item.id === this.form.type) {
          this.unit = item.unit // 单位 1-天 2-半天 3-小时
          if (item.unit == 1) {
            this.halfDay_s = '' // 开始的上午下午
            this.halfDay_e = '' // 结束的上午下午
            this.startTimeSon = ''
            this.endTimeSon = ''
          } else if (item.unit == 2) {
            this.startTimeSon = ''
            this.endTimeSon = ''
          } else {
            this.halfDay_s = '' // 开始的上午下午
            this.halfDay_e = '' // 结束的上午下午
          }
        }
      }
      console.log('this.unit:', this.unit)
      this.changeDayTime()
    },
    reset() {
      this.form = {
        type: '', // 1-事假2-病假3-调休4-产假5-婚假6-例假7-哺乳假8-丧假
        startTime: '', // 开始时间
        endTime: '', // 结束时间
        time: '', // 时长
        content: '', // 原因
        file: '', // 附件
        flowId: '', // 审核流程id
        nowUser: '', // 当前审核人
      }
      this.startTimeDay = ''
      this.startTimeSon = ''
      this.endTimeDay = ''
      this.endTimeSon = ''
      this.leaveDay = []
      this.house = ''
      this.halfDay_s = ''
      this.halfDay_e = ''
      this.unit = ''
      this.$emit('reset')
      this.$modal.closeLoading();
    },
    // 请假类型
    getruleList() {
      listLeaveUSer({
        deptIds: this.deptId
      }).then(response => {
        this.ruleList = response.data;
      });
    },
    // 比较两个时间相隔几天，几小时
    changeDayTime() {
      // 小时
      let date1 = new Date(this.startTimeDay);
      // 创建第二个时间对象
      let date2 = new Date(this.endTimeDay);
      // 计算两个时间相隔的天数
      let diffInDays = Math.floor((date2 - date1) / (1000 * 60 * 60 * 24));
      let leaveDay_ = [] // 每天统计明细分钟/天数
      let leaveDetail = []
      let allCount = 0 // 总时长/总天数
      let a_s = new Date(`${this.startTimeDay} 00:00:00`).getTime()
      let a_e = new Date(`${this.endTimeDay} 00:00:00`).getTime()
      if (a_e < a_s) {
        this.$message.error('请正确选择请假日期')
        return
      }
      if (this.unit == 3 && this.startTimeDay && this.startTimeSon && this.endTimeDay && this.endTimeSon) {
        // 获取两个时间之间的每一天

        let hour = 0 // 一共几小时
        let minute = 0 // 一共几分钟
        for (let i = 0; i < diffInDays + 1; i++) {
          let currentDay = new Date(date1.getTime() + (i * 24 * 60 * 60 * 1000));
          let day_ = currentDay.toLocaleString()
          let a_ = day_.split(' ')[0].split('/')
          let firstDayOfMonth = new Date(a_[0], a_[1] - 1, a_[2])
          // 0表示周日，1表示周一...6表示周六
          let dayWeek = firstDayOfMonth.getDay()
          // 计算每日请假的时长
          // workDay 0 序列号代表周一
          hour = hour + this.timeCountDay(a_.join('-'), diffInDays + 1, dayWeek, i).hour
          minute = minute + this.timeCountDay(a_.join('-'), diffInDays + 1, dayWeek, i).minute
          allCount = allCount + this.timeCountDay(a_.join('-'), diffInDays + 1, dayWeek, i).allMinue
          leaveDay_.push({
            week: dayWeek,
            day: a_.join('-'),
            content: this.workDay[dayWeek ? dayWeek - 1 : 6] ? 2 : 0,
            isholiday: this.workDay[dayWeek ? dayWeek - 1 : 6] ? 0 : 1, // 是否休假
            woorData: this.workDay[dayWeek ? dayWeek - 1 : 6] ? JSON.parse(JSON.stringify(this.workDay[dayWeek ? dayWeek - 1 : 6])) : null, // 工作时间明细
            leavetime: this.timeCountDay(a_.join('-'), diffInDays + 1, dayWeek, i).timeline,
            number: this.timeCountDay(a_.join('-'), diffInDays + 1, dayWeek, i).number,
          })
          if (this.workDay[dayWeek ? dayWeek - 1 : 6]) {
            leaveDetail.push({
              day: a_.join('-'),
              time: this.timeCountDay(a_.join('-'), diffInDays + 1, dayWeek, i).number
            })
          }
        }
        console.log('hour===>', hour, minute)
// 让超出的分钟进行取整加入小时
        hour = hour + Math.floor(minute / 60)
        minute = minute % 60

        this.house = parseFloat(`${hour}.${minute < 10 ? '0' + minute : minute}`)
        this.$emit('checkExamine', {
          unit: this.unit,
          data: parseFloat(`${hour}.${minute < 10 ? '0' + minute : minute}`)
        }) // 判断审核流程
      }
      // 按半天  && this.halfDay_s && this.halfDay_e
      if (this.unit == 2 && this.startTimeDay && this.endTimeDay && this.halfDay_s && this.halfDay_e) {
        // 1 上午 2 下午
        // 如果是固定排班需要排除休息日
        for (let i = 0; i < diffInDays + 1; i++) {
          let currentDay = new Date(date1.getTime() + (i * 24 * 60 * 60 * 1000));
          let day_ = currentDay.toLocaleString()
          let a_ = day_.split(' ')[0].split('/')
          let firstDayOfMonth = new Date(a_[0], a_[1] - 1, a_[2])
          // 0表示周日，1表示周一...6表示周六
          let dayWeek = firstDayOfMonth.getDay()
          let number_ = 0
          if (diffInDays + 1 == 1) {
            if (this.halfDay_s == this.halfDay_e) {
              number_ = 0.5
            } else {
              number_ = 1
            }
          } else {
            if (i == 0) {
              number_ = this.halfDay_s == 1 ? 1 : 0.5
            } else if (i == diffInDays) {
              number_ = this.halfDay_e == 2 ? 1 : 0.5
            } else {
              number_ = 1
            }
          }
          allCount = allCount + (this.workDay[dayWeek ? dayWeek - 1 : 6] ? number_ : 0)
          leaveDay_.push({
            day: a_.join('-'),
            week: dayWeek,
            isholiday: this.workDay[dayWeek ? dayWeek - 1 : 6] ? 0 : 1, // 是否休假
            woorData: this.workDay[dayWeek ? dayWeek - 1 : 6] ? this.$deepCopy(this.workDay[dayWeek ? dayWeek - 1 : 6]) : null, // 工作时间明细
            number: this.workDay[dayWeek ? dayWeek - 1 : 6] ? number_ : 0
          })
          if (this.workDay[dayWeek ? dayWeek - 1 : 6]) {
            leaveDetail.push({
              day: a_.join('-'),
              time: number_
            })
          }
        }
        this.house = allCount
        this.$emit('checkExamine', {unit: this.unit, data: allCount}) // 判断审核流程
      }
      // 按天
      // halfDay_s: '', // 开始的上午下午
      //   halfDay_e: '', // 结束的上午下午
      //   startTimeDay: '',
      //   endTimeSon: '',
      if (this.unit == 1 && this.startTimeDay && this.endTimeDay) {
        // 如果是固定排班需要排除休息日
        for (let i = 0; i < diffInDays + 1; i++) {
          let currentDay = new Date(date1.getTime() + (i * 24 * 60 * 60 * 1000));
          let day_ = currentDay.toLocaleString()
          let a_ = day_.split(' ')[0].split('/')
          let firstDayOfMonth = new Date(a_[0], a_[1] - 1, a_[2])
          // 0表示周日，1表示周一...6表示周六
          let dayWeek = firstDayOfMonth.getDay()
          allCount = allCount + (this.workDay[dayWeek ? dayWeek - 1 : 6] ? 1 : 0)
          leaveDay_.push({
            day: a_.join('-'),
            week: dayWeek,
            isholiday: this.workDay[dayWeek ? dayWeek - 1 : 6] ? 0 : 1, // 是否休假
            woorData: this.workDay[dayWeek ? dayWeek - 1 : 6] ? this.$deepCopy(this.workDay[dayWeek ? dayWeek - 1 : 6]) : null, // 工作时间明细
            number: this.workDay[dayWeek ? dayWeek - 1 : 6] ? 1 : 0
          })
          if (this.workDay[dayWeek ? dayWeek - 1 : 6]) {
            leaveDetail.push({
              day: a_.join('-'),
              time: 1
            })
          }
        }
        this.house = allCount
        this.$emit('checkExamine', {unit: this.unit, data: allCount}) // 判断审核流程
      }
      this.leaveDay = leaveDay_.length ? leaveDay_ : []
      this.form.time = allCount
    },
    timeCountDay(day, countDay, week, index) {
      console.log('day, countDay, week, index:', day, countDay, week, index)
      // index 请假天数序列号
      // 每天请假做长时间 workDay中workTime
      // rest // 中午休息时间
      if (this.workDay[week ? week - 1 : 6]) {
        let start_Time = new Date(`${day} ${this.startTimeSon}`).getTime() // 开始时间时间戳
        let start_time_division = this.startTimeSon
        let end_Time = new Date(`${day} ${this.endTimeSon}`).getTime() // 结束时间时间戳
        let end_time_division = this.endTimeSon
        let start_a = new Date(`${day} ${this.workDay[week ? week - 1 : 6].comeTime1}`).getTime() // 排班的开始时间
        let end_a = new Date(`${day} ${this.workDay[week ? week - 1 : 6].outTime1}`).getTime()
        let rest_ = JSON.parse(this.workDay[week ? week - 1 : 6].rest) // 中间休息时间
        let timeline = []

        if (countDay == 1) {
          if (start_Time <= start_a) {
            start_Time = start_a
            start_time_division = this.workDay[week ? week - 1 : 6].comeTime1
          }
          if (end_Time > end_a) {
            end_Time = end_a
            end_time_division = this.workDay[week ? week - 1 : 6].outTime1
          }
        } else {
          if (index) {
            start_Time = start_a
            start_time_division = this.workDay[week ? week - 1 : 6].endComeTime1
            if (countDay - 1 === index) {
              // 进行比较结束时间
              if (end_Time > end_a) {
                end_Time = end_a
                end_time_division = this.workDay[week ? week - 1 : 6].endOutTime1
              }
            } else {
              end_Time = end_a
              end_time_division = this.workDay[week ? week - 1 : 6].endOutTime1
            }
          } else {
            // 开始时间
            if (start_Time <= start_a) {
              start_Time = start_a
              start_time_division = this.workDay[week ? week - 1 : 6].endComeTime1
            }
            end_Time = end_a
            end_time_division = this.workDay[week ? week - 1 : 6].endOutTime1
          }
        }
        // 计算当天请假时间中间的休息时长，休息时长不算入请假时长 end start
        let rest_time = 0 // 需要计算出休息时长几分钟
        let rest_list = [] // 计算每一组休息时间
        for (let item of rest_) {
          let rest_start = new Date(`${day} ${item.start}`).getTime() // 休息段开始时间
          let rest_end = new Date(`${day} ${item.end}`).getTime() // 休息段结束时间
          let start_ = '' // 休息可开始时间
          let end_ = '' // 休息可结束时间
          let status_ = true
          if (start_Time < rest_start) {
            start_ = rest_start
          } else if (start_Time > rest_start) {
            if (start_Time < rest_end) {
              start_ = start_Time
            } else {
              rest_list.push(0) // 这个休息段时长0
              status_ = false
            }
          }
          if (end_Time < rest_start) {
            rest_list.push(0) // 这个休息段时长0
            status_ = false
          } else if (end_Time > rest_start) {
            if (end_Time < rest_end) {
              end_ = end_Time
            } else {
              end_ = rest_end
            }
          }
          // 计算两个时间差
          if (status_) {
            let a_ = new Date(start_);
            let b_ = new Date(end_);
            let c_ = Math.abs(b_ - a_); // 获取两个日期对象之间的毫秒数差值（正负都包括）
            let d_ = Math.floor((c_ / (60 * 1000))); // 分钟
            rest_list.push(d_)
          }

        }
        for (let item of rest_list) {
          rest_time = rest_time + item
        }

        let date1 = new Date(start_Time);
        let date2 = new Date(end_Time);
        let diffInMilliseconds = Math.abs(date2 - date1); // 获取两个日期对象之间的毫秒数差值（正负都包括）
        let minutesDiff = Math.floor((diffInMilliseconds / (60 * 1000))); // 分钟
        console.log('minutesDiff=====>:', minutesDiff, rest_time)
        // 一天超出最长的请假时长无需请假
        minutesDiff = minutesDiff - rest_time
        if (minutesDiff > this.workDay[week ? week - 1 : 6].workTime) {
          minutesDiff = this.workDay[week ? week - 1 : 6].workTime
        }
        let minutesDiff_m = minutesDiff % 60
        let number_ = parseFloat(`${Math.floor(minutesDiff / 60)}.${minutesDiff_m < 10 ? '0' + minutesDiff_m : minutesDiff_m}`)

        timeline.push(
          {
            startTime: start_time_division,
            endTime: end_time_division
          }
        )
        return {
          timeline: timeline,
          number: number_,
          hour: Math.floor(minutesDiff / 60),
          minute: minutesDiff_m,
          allMinue: minutesDiff
        }
      } else {
        return {timeline: 0, number: 0, hour: 0, minute: 0, allMinue: 0}
      }
    }
  }
}
</script>

<style scoped>

.line {
  text-align: center;
}

.tips-rule {
  color: #999;
  font-size: 12px;
}

.tips-rule span {
  color: #2a99ff;
  cursor: pointer;
}

</style>
